/*
 * GoodsCacheCmd
 * Copyright (c) 2019 taisu Inc., All rights reserved.
 * This software is the confidential and proprietary information of
 * taisu Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with tysu.com.cn.
 */

package com.ymk.cmd;

import com.alibaba.fastjson.JSON;
import com.ymk.base.cmd.ACmd;
import com.ymk.base.cmd.CmdSign;
import com.ymk.base.utlis.ParamsBuilder;
import com.ymk.bo.goods.GoodsBO;
import com.ymk.bo.goods.GoodsCatBO;
import com.ymk.core.code.cmd.GoodsCmdCode;
import com.ymk.core.constants.SysConstants;
import com.ymk.core.enums.goods.GoodsCatStatusEnum;
import com.ymk.core.enums.goods.GoodsStatusEnum;
import com.ymk.mq.MessageSender;
import com.ymk.service.IGoodsCatService;
import com.ymk.service.IGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class GoodsCatCacheCmd extends ACmd {

    @Override
    public CmdSign execute(HttpServletRequest request, CmdSign sign) throws Exception {
        CmdSign respSign = new CmdSign(sign);
        GoodsCatBO reqData = super.getData(sign, GoodsCatBO.class);
        ParamsBuilder paramsBuilder = ParamsBuilder.newBuild()
                .addParam("mchId", reqData.getMchId())
                .addParam("status", GoodsCatStatusEnum.NORMAL.getStatus());

        List<GoodsCatBO> goodsCatBOList = this.goodsCatService.list(paramsBuilder.build());
        for (GoodsCatBO goodsCatBO : goodsCatBOList) {
            paramsBuilder.clearParam()
                    .addParam("catId", goodsCatBO.getId())
                    .addParam("status", GoodsStatusEnum.NORMAL.getStatus())
                    .addParam("loadCat", true)
                    .addParam("loadSku", true)
                    .addParam("orderBySalesVolumeDesc", true);
            List<GoodsBO> list = this.goodsService.list(paramsBuilder.build());
            goodsCatBO.setGoodsBOList(list);
        }

        // 设置redis 缓存
        this.redisTemplate.opsForValue().set(SysConstants.REDIS_KEY_GOODS_CAT + reqData.getMchId().toString(), JSON.toJSONString(goodsCatBOList));
        return respSign;
    }

    @Override
    public String getCmdCode() {
        return GoodsCmdCode.GOODS_CAT_CACHE;
    }

    @Override
    public boolean anon(CmdSign sign) {
        return true;
    }

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IGoodsCatService goodsCatService;
    @Autowired
    private MessageSender messageSender;

}
